<?php

namespace app\store\job;

use think\facade\Db;
use think\facade\Queue;
use think\queue\Job;

/**
 *
 * 拼团活动结算队列
 * */
class Activity
{
    public function fire(Job $job, $data)
    {
        echo '执行次数:'.$job->attempts().PHP_EOL;
        if ($job->attempts()>3){
             echo '重试次数:'.$job->attempts();
             $job->delete();
        }


        /**
         * 成功处理
         * */
        echo date('Y-m-d H:i:s').'请求参数:'.json_encode($data).PHP_EOL;
        Db::startTrans();
        try {

            $success = $data['success_rule'];
            $fail = $data['fail_rule'];

            $success_gift = [];
            if ($success['integral']>0){
                $success_gift['integral'] = $success['integral'];
            }

            if ($success['balance']>0){
                $success_gift['balance'] = $success['balance'];
            }

            $success_gift['status'] = 2;


            $fail_gift = [];
            if ($fail['integral']>0){
                $fail_gift['integral'] = $fail['integral'];

            }

            if ($fail['balance']>0){
                $fail_gift['balance'] = $fail['balance'];
            }

            $fail_gift['status'] = -1;
            echo date('Y-m-d H:i:s').'请求参数$$fail_gift:'.json_encode($fail_gift).PHP_EOL;
            echo date('Y-m-d H:i:s').'请求参数$$success_gift:'.json_encode($success_gift).PHP_EOL;
            $result = false;
            $success_gift['utime'] = time();
            $rst = Db::name('group_activity_record')
                ->where(['group_activity_id' => $data['group_activity_id'],'user_id' => $data['user_id']])
                ->update($success_gift);
            echo date('Y-m-d H:i:s').'返回值rst:'.$rst.PHP_EOL;
            echo date('Y-m-d H:i:s').'返回值rstsql:'.Db::name('group_activity_record')->getLastSql().PHP_EOL;
            $this->saveSuccessAwardQueue($data['user_id'],$success_gift);

            if (!empty($data['ids'])){
                /**
                 * 失败处理
                 * */
                $fail_gift['utime'] = time();
               $res =  Db::name('group_activity_record')
                    ->where('group_activity_id',$data['group_activity_id'])
                    ->whereIn('user_id',$data['ids'])
                    ->update($fail_gift);

                echo date('Y-m-d H:i:s').'返回值res:'.$res.PHP_EOL;
                /**
                 *  发放奖励
                 * */
                $this->saveFailAwardQueue($data['ids'],$fail_gift);

                /**
                 * 进行退款
                 * */
                $this->saveFailRefundQueue($data['store_id'],$data['group_orders']);
            }
            Db::commit();
            $result = true;
        } catch (\Exception $e){
            Db::rollback();
            echo date('Y-m-d H:i:s').'异常:'.$e->getMessage().PHP_EOL;
//            var_dump($e->getMessage());
        }

        if ($result){
            $job->delete();
        }


    }


    public function failed($data)
    {
        Db::name('failed_jobs')->insert([
            'payload' => $data
        ]);
    }


    /**
     * 成功奖励余额或积分
     * */

    protected function saveSuccessAwardQueue($user_id,$success_gift)
    {
        echo '进入成功奖励余额或积分'.PHP_EOL;
        /**
         * 成功奖励
         * */
        if (isset($success_gift['integral'])){
            $rst = Queue::push('app\store\job\Account@integral',[
                'user_id' => $user_id,
                'desc' => '拼团活动奖励',
                'change_type'=>1,
                'integral' => $success_gift['integral']
            ],'userAccount');
            echo '加入奖励队列$rst'.$rst.PHP_EOL;
        }

        if (isset($success_gift['balance'])){
            $rst1 = Queue::push('app\store\job\Account@balance',[
                'user_id' => $user_id,
                'desc' => '拼团活动奖励',
                'change_type'=>1,
                'balance' => $success_gift['balance']
            ],'userAccount');
            echo '加入积分队列$rst'.$rst1.PHP_EOL;
        }
    }


    /**
     * 失败奖励余额或积分
     * */

    protected function saveFailAwardQueue($user_ids,$fail_gift)
    {
        echo '进入失败奖励余额或积分'.PHP_EOL;
        /**
         * 失败奖励
         * */
        foreach ($user_ids as $v){

            if (isset($fail_gift['integral'])){
               $rst = Queue::push('app\store\job\Account@integral',[
                    'user_id' => $v,
                    'desc' => '拼团活动奖励',
                    'change_type'=>1,
                    'integral' => $fail_gift['integral']
                ],'userAccount');
                echo '加入失败奖励队列$rst'.$rst.PHP_EOL;
            }

            if (isset($fail_gift['balance'])){
                $rs = Queue::push('app\store\job\Account@balance',[
                    'user_id' => $v,
                    'desc' => '拼团活动奖励',
                    'change_type'=>1,
                    'balance' => $fail_gift['balance']
                ],'userAccount');
                echo '加入失败积分队列$rst'.$rs.PHP_EOL;
            }


        }
    }


    /**
     * 失败退款
     * */

    protected function saveFailRefundQueue($store_id,$group_orders)
    {
        echo '进入失败退款'.PHP_EOL;
        $config = $this->getPaymentConfig($store_id);
        echo '获取支付信息$group_orders'.json_encode($group_orders).PHP_EOL;
        foreach ($group_orders as $v) {
            echo '获取支付信息payment_type'.json_encode($v).PHP_EOL;
            $queueRst = [
                'group_order_id' => $v['group_order_id'],
                'payment_type' => $v['payment_type'],
                'out_trade_no' => $v['out_trade_no'],
                'config' => $config[$v['payment_type']],
                'refund_fee' => $v['real_amount']
            ];
//            echo '获取支付信息$$queueRst'.json_encode($queueRst).PHP_EOL;
            $rst = Queue::push('app\store\job\Refund',$queueRst ,'userRefund');
            echo '加入失败退款队列$rst'.$rst.PHP_EOL;
        }
    }




}